package br.com.jk.util;

import br.com.jk.config.Cfg;
import br.com.jk.config.CfgPropUtil;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.Transaction;
import org.hibernate.boot.registry.StandardServiceRegistryBuilder;
import org.hibernate.cfg.Configuration;
import org.hibernate.service.ServiceRegistry;

/**
 *
 * @author camilo
 */
public class HibernateUtil {

  private static final SessionFactory factory;
  private static final ServiceRegistry registry;
  private static SessionFactory factoryMix;
  private static ServiceRegistry registryMix;

  static {
    Configuration cfg = new Configuration();
    cfg.configure("hibernate.cfg.xml");

    CfgPropUtil propUt = new CfgPropUtil();
    Cfg prop = propUt.getCfgProp();
    cfg.setProperty("hibernate.connection.url",
            "jdbc:postgresql://" + prop.getIp() + ":" + prop.getPorta() + "/" + prop.getNomeBd());
    cfg.setProperty("hibernate.connection.username", prop.getUser());
    cfg.setProperty("hibernate.connection.password", prop.getPassword());

    registry
            = new StandardServiceRegistryBuilder().applySettings(cfg.getProperties()).build();
    factory = cfg.buildSessionFactory(registry);
  }

  public static SessionFactory getSessionFactory() {

    return factory;
  }

  public static SessionFactory getSessionFactoryMixDB() {
    Configuration cfgmix = new Configuration();
    cfgmix.configure("hibernatemix.cfg.xml");
    /*cfgmix.setProperty("hibernate.dialect", "org.hibernate.dialect.PostgreSQL82Dialect");
     cfgmix.setProperty("hibernate.connection.driver_class", "org.postgresql.Driver");
     cfgmix.setProperty("hibernate.connection.url", "jdbc:postgresql://127.0.0.1:5432/mixdb");
     cfgmix.setProperty("hibernate.connection.username", "postgres");
     cfgmix.setProperty("hibernate.connection.password", "rp1064");
     cfgmix.setProperty("hibernate.current_session_context_class", "thread");
     cfgmix.setProperty("show_sql", "true");
     cfgmix.setProperty("format_sql", "true");
     cfgmix.addAnnotatedClass(CotacaoCompra.class);*/
    registryMix = new StandardServiceRegistryBuilder().applySettings(cfgmix.getProperties()).build();
    factoryMix = cfgmix.buildSessionFactory(registryMix);
    return factoryMix;
  }

  public static void IniciaConexao(Transaction transacao, Session session) {
    transacao = session.beginTransaction();
  }

  public static void Commit(Transaction transacao) {
    transacao.commit();
  }
}
